<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="Spu名称">
        <el-input v-model="spu.spuName" placeholder="Spu名称" />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option
            v-for="tm in tradeMarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Spu描述">
        <el-input v-model="spu.description" type="textarea" rows="3" placeholder="描述" />
      </el-form-item>
      <el-form-item label="Spu图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImgList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="attrIdAndAttrName"
          :placeholder="`还有${unSelectSaleAttr.length}个未选择`"
        >
          <el-option
            v-for="unselect in unSelectSaleAttr"
            :key="unselect.id"
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
          />
        </el-select>
        <el-button
          style="margin-left: 20px"
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
        >添加销售属性</el-button>
        <el-table
          style="width: 100%; margin-top: 20px"
          border
          :data="spu.spuSaleAttrList"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="saleAttrName" label="属性名" width="width" />
          <el-table-column prop="saleAttrValueName" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                :disable-transitions="false"
                @close="handleClose(row, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.inputVisible"
                ref="saveTagInput"
                v-model="row.inputValue"
                class="input-new-tag"
                size="small"
                @blur="handleInputConfirm(row)"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
              >+ 新内容</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="80" align="center">
            <template slot-scope="{ $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // inputVisible: false,
      // inputValue: '',
      spu: {
        // 三级分类Id
        category3Id: 0,
        // 描述
        description: '',
        // spu名称
        spuName: '',
        // 品牌id
        tmId: '',
        // 手机spu图片信息
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: 'string',
          //   imgUrl: 'string',
          //   spuId: 0
          // }
        ],
        // 平台属性与属性值的收集
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: 'string',
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: 'string',
          //       saleAttrName: 'string',
          //       saleAttrValueName: 'string',
          //       spuId: 0
          //     }
          //   ]
          // }
        ]
      },
      // 收集未选择属性的Id
      attrIdAndAttrName: '',
      tradeMarkList: [],
      spuImgList: [],
      saleAttrList: []
    }
  },
  computed: {
    /**
     * 获取该商品还未拥有的销售属性
     * everyAttrList：所有的销售属性
     * haveAttrList：该商品已经有的销售属性
     */
    unSelectSaleAttr() {
      const result = this.saleAttrList.filter((everyAttrList) => {
        return this.spu.spuSaleAttrList.every((haveAttrList) => {
          return everyAttrList.name != haveAttrList.saleAttrName
        })
      })
      return result
    }
  },
  methods: {
    // 移除图片回调
    handleRemove(file, fileList) {
      this.spuImgList = fileList
    },
    // 预显示图片回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 照片墙图片上传成功的回调
    handleSuccess(response, file, fileList) {
      this.spuImgList = fileList
    },
    // 关闭tag标签回调
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1)
    },
    // 展示tag输入框回调 | 输入新添加的属性值
    showInput(row) {
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'inputValue', '')
    },
    // tag的input失去焦点回调 | 保存新添加的属性值
    handleInputConfirm(row) {
      const { baseSaleAttrId, inputValue } = row
      const newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
      // 属性值不能为空
      if (inputValue.trim() == '') {
        return this.$message({
          message: '属性值不能为空',
          type: 'warning'
        })
      }
      // 属性值不能重复
      const result = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName == inputValue
      )
      // 重复不能添加
      if (result) {
        return this.$message({
          message: '属性值不能重复',
          type: 'warning'
        })
      }
      row.spuSaleAttrValueList.push(newSaleAttrValue)
      row.inputVisible = false
    },
    // 初始化spuForm数据
    async initSpuForm(row) {
      // 获取Spu信息
      const spuInfo = await this.$API.spu.reqGetSpuInfoById(row.id)
      if (spuInfo.code == 200) {
        this.spu = spuInfo.data
      }

      // 获取品牌信息
      const tradeMark = await this.$API.spu.reqGetTradeMark()
      if (tradeMark.code == 200) {
        this.tradeMarkList = tradeMark.data
      }

      // 获取spu图片列表
      const imgList = await this.$API.spu.reqSpuImageList(row.id)
      if (imgList.code == 200) {
        const listArr = imgList.data
        listArr.forEach((item) => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImgList = listArr
      }

      // 获取销售属性
      const saleAttrList = await this.$API.spu.reqBaseSaleAttrList()
      if (saleAttrList.code == 200) {
        this.saleAttrList = saleAttrList.data
      }
    },
    // 添加新的销售属性
    addSaleAttr() {
      const [baseAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      const newSaleAttr = { baseAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      this.attrIdAndAttrName = ''
    },
    // 保存按钮的回调
    async addOrUpdateSpu() {
      // 整理参数
      this.spu.spuImageList = this.spuImgList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url
        }
      })
      const result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
      if (result.code == 200 || result.code == 201) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.$emit('changeScene', { scene: 0, flag: this.spu.id ? '修改' : '添加' })
      }
      Object.assign(this._data, this.$options.data())
    },
    // 添加spu回调函数
    async addSpuData(cate3Id) {
      this.spu.category3Id = cate3Id
      // 获取品牌信息
      const tradeMark = await this.$API.spu.reqGetTradeMark()
      if (tradeMark.code == 200) {
        this.tradeMarkList = tradeMark.data
      }
      // 获取销售属性
      const saleAttrList = await this.$API.spu.reqBaseSaleAttrList()
      if (saleAttrList.code == 200) {
        this.saleAttrList = saleAttrList.data
      }
    },
    // 取消按钮的回调
    cancel() {
      this.$emit('changeScene', { scene: 0, flag: '' })
      Object.assign(this._data, this.$options.data())
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
